<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态 " clearable>
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" type="index" width="80" />
      <el-table-column label="合作商家名称" align="center" prop="merchantName" />
      <el-table-column label="商家地址" align="center" prop="merchantAddress" />
      <el-table-column label="商家电话" align="center" prop="merchantPhone" />
      <el-table-column label="订单状态 " align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="orderNumber" />
      <el-table-column label="送货员" align="center" prop="empId">
        <template #default="scope">
          {{ getEmployeeName(scope.row.empId) }}
        </template>
      </el-table-column>
      <el-table-column label="所属区域" align="center" prop="regionId">
        <template #default="scope">
          {{ getRegionName(scope.row.regionId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          
          <el-button 
            link 
            type="danger" 
            @click="handleCancel(scope.row)" 
            :disabled="scope.row.status !== 1"
          >
            取消订单
          </el-button>
          <el-button link type="primary" @click="handleViewDetail(scope.row)">订单详细</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看订单详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions border :column="2">
        <el-descriptions-item label="订单ID">{{ detailForm.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ detailForm.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="合作商家">{{ detailForm.merchantName }}</el-descriptions-item>
        <el-descriptions-item label="商家电话">{{ detailForm.merchantPhone }}</el-descriptions-item>
        <el-descriptions-item label="商家地址">{{ detailForm.merchantAddress }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="order_status" :value="detailForm.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="所属区域">{{ getRegionName(detailForm.regionId) }}</el-descriptions-item>
        <el-descriptions-item label="送货员">{{ getEmployeeName(detailForm.empId) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailForm.updateTime }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="center">商品明细</el-divider>
      <el-table :data="detailForm.tbOrderDetailList" style="width: 100%">
        <el-table-column label="商品ID" prop="productId" align="center" />
        <el-table-column label="商品名称" prop="productName" align="center" />
        <el-table-column label="数量" prop="number" align="center" />
        <el-table-column label="单价" prop="unitPrice" align="center" />
        <el-table-column label="总价" prop="totalPrice" align="center" />
      </el-table>
      
      <el-descriptions border :column="1" style="margin-top: 20px;">
        <el-descriptions-item label="订单总金额">¥{{ calculateTotalAmount(detailForm.tbOrderDetailList) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, updateOrder, delOrder } from "@/api/manage/order"
import { listEmp } from "@/api/manage/emp"
import { listRegion } from "@/api/manage/region"
import { getUserProfile } from "@/api/system/user"

const { proxy } = getCurrentInstance()
const { order_status } = proxy.useDict('order_status')

const orderList = ref([])
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const detailTitle = ref("")
const merchantId = ref(null)

// 员工列表
const employees = ref([])
// 区域列表
const regions = ref([])

const data = reactive({
  detailForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantName: null,
    merchantPhone: null,
    status: null,
    orderNumber: null,
    empId: null,
    regionId: null
  }
})

const { queryParams, detailForm } = toRefs(data)

/** 查询货单管理列表 */
function getList() {
  loading.value = true
  // 添加商家ID查询条件
  const query = {
    ...queryParams.value,
    merchantId: merchantId.value
  }
  listOrder(query).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询员工列表 */
function getEmployees() {
  listEmp().then(response => {
    employees.value = response.rows
  })
}

/** 查询区域列表 */
function getRegions() {
  listRegion().then(response => {
    regions.value = response.rows
  })
}

// 获取当前用户信息
function getCurrentUser() {
  return new Promise((resolve, reject) => {
    getUserProfile().then(response => {
      if (response.code === 200 && response.data) {
        merchantId.value = response.data.userId
        resolve(response.data.userId)
      } else {
        reject(new Error('无法获取用户信息'))
      }
    }).catch(error => {
      console.error('获取用户信息失败:', error)
      proxy.$modal.msgError("获取用户信息失败")
      reject(error)
    })
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 查看详情操作 */
function handleViewDetail(row) {
  getOrder(row.orderId).then(response => {
    detailForm.value = response.data
    detailOpen.value = true
    detailTitle.value = "订单详情 - " + response.data.orderNumber
  })
}

/** 已送达操作 */
function handleDelivered(row) {
  proxy.$modal.confirm('是否确认将订单"' + row.orderNumber + '"标记为已送达？').then(() => {
    const updateData = {
      ...row,
      status: 4, // 已送达状态
      tbOrderDetailList: row.tbOrderDetailList
    }
    
    return updateOrder(updateData)
  }).then(() => {
    proxy.$modal.msgSuccess("订单状态修改成功")
    getList()
  }).catch(() => {})
}

/** 取消订单操作 */
function handleCancel(row) {
  proxy.$modal.confirm('是否确认取消订单"' + row.orderNumber + '"？').then(() => {
    return delOrder(row.orderId)
  }).then(() => {
    proxy.$modal.msgSuccess("订单取消成功")
    getList()
  }).catch(() => {})
}

/** 计算订单总金额 */
function calculateTotalAmount(details) {
  if (!details || details.length === 0) return 0
  return details.reduce((total, item) => {
    return total + (parseFloat(item.totalPrice) || 0)
  }, 0).toFixed(2)
}

/** 根据员工ID获取员工姓名 */
function getEmployeeName(empId) {
  if (!empId) return ''
  const employee = employees.value.find(emp => emp.employeeId === empId)
  return employee ? employee.name : empId
}

/** 根据区域ID获取区域名称 */
function getRegionName(regionId) {
  if (!regionId) return ''
  const region = regions.value.find(r => r.regionId === regionId)
  return region ? region.name : regionId
}

// 初始化时获取员工和区域数据
onMounted(() => {
  getEmployees()
  getRegions()
  
  // 获取当前用户信息，然后获取订单列表
  getCurrentUser().then(() => {
    if (merchantId.value) {
      getList()
    }
  }).catch((error) => {
    console.error('初始化失败:', error)
    proxy.$modal.msgError("页面初始化失败")
  })
})
</script>